package com.wlyuan.index.infrastructure.utils;

import cn.hutool.core.util.ReflectUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.var;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class MergeUtils {
    private static <T> List<T> intersect(List<T> a, List<T> b) {
        return new ArrayList<>(CollectionUtils.intersection(a, b));
    }

    private static <T> Set<T> intersect(Set<T> a, Set<T> b) {
        return new HashSet<>(CollectionUtils.intersection(a, b));
    }

    private static Object[] intersect(Object[] a, Object[] b) {
        return intersect(Arrays.asList(a), Arrays.asList(b)).toArray();
    }

    private static <T> T fill(Class<T> mergeClass, T a, T b) throws IllegalAccessException {
        var fields = ReflectUtil.getFields(mergeClass);
        for (var field : fields) {
            field.setAccessible(true);
            var value1 = field.get(a);
            var value2 = field.get(b);
            if (null == value2) {
                continue;
            }

            // 设置为value2
            if (null == value1) {
                field.set(a, value2);
                continue;
            }

            // 数组取交集
            if (value2 instanceof List) {
                field.set(a, intersect((List) value1, (List) value2));
            } else if (value2 instanceof Set) {
                field.set(a, intersect((Set) value1, (Set) value2));
            } else if (value2.getClass().isArray()) {
                field.set(a, intersect((Object[]) value1, (Object[]) value2));
            } else {
                field.set(a, value2);
            }
        }

        return a;
    }

    public static <T> T fill(T a, T b) {
        if (null == a) {
            return b;
        }
        try {
            return fill((Class<T>) a.getClass(), a, b);
        } catch (IllegalAccessException e) {
            return a;
        }
    }
}
